/*
 * @Date: 2022-07-06 17:31:27
 * @LastEditTime: 2022-07-06 17:57:29
 * @Description: file content
 * @FilePath: \part\fronts-cli\npmScripts\writePkgScript.js
 */
const rpkg = require('../package.json')
const resolveCwd = require("./resolveCwd")
const jsonUtil = require('./jsonUtil')
const { exitError, exitSuccess } = require('./exit')
const EXIT_CODE = require('./exitCode')

const writePkgScript = (scriptKey, scriptValue, isEdit) => {
  const modeCn = isEdit ? '修改' : '新增'
  const pkgDir = resolveCwd('package.json')
  
  let pkg = null
  try {
    pkg = jsonUtil.readData(pkgDir)
  } catch (err) {
    console.log(err,pkgDir)
    exitError(EXIT_CODE.LACK_PACKAGE)
  }

  if (!pkg.scripts) {
    pkg['scripts'] = {}
  }

  if (!isEdit && pkg.scripts[scriptKey]) {
    exitError(EXIT_CODE.EXISTS_SCRIPTKEY(rpkg.name, scriptKey, scriptValue))
  }

  pkg.scripts[scriptKey] = scriptValue
  jsonUtil.wirteData(pkgDir, pkg)
  exitSuccess(`已${modeCn} ${scriptKey} ${scriptValue}`)
}

module.exports = writePkgScript